package cn.bjxy.shishaolong.system.user.controller;

import cn.bjxy.shishaolong.common.ResultMsg;
import cn.bjxy.shishaolong.common.StatusCode;
import cn.bjxy.shishaolong.common.SysConst;
import cn.bjxy.shishaolong.system.annotation.Permission;
import cn.bjxy.shishaolong.system.exception.OperatorFailureException;
import cn.bjxy.shishaolong.system.service.IRoleService;
import cn.bjxy.shishaolong.system.user.entity.SysUserInfo;
import cn.bjxy.shishaolong.system.user.entity.SysUserLocalAuthen;
import cn.bjxy.shishaolong.system.user.service.ISysUserInfoService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户管理前端控制器
 * </p>
 *
 * @author 时少龙
 * @since 2019-03-09
 */
@RestController
@RequestMapping("/api/admin/um/user")
@CrossOrigin
public class UserManageController {

    @Autowired
    private ISysUserInfoService userInfoService;
    @Autowired
    private IRoleService roleService;

    /**
     * 查询用户信息
     *
     * @param param
     * @return
     */
    @RequestMapping("/queryByCondition")
    @Permission
    public ResultMsg queryByCondition(@RequestBody JSONObject param) {
        try {
            //查询条件
            SysUserInfo userInfo = null;
            if (param.containsKey(SysConst.QUERY_CONDITION_KEY)) {
                userInfo = param.getObject(SysConst.QUERY_CONDITION_KEY, SysUserInfo.class);
                // 安全校验，如果查询的不是老师或学生角色，将这一查询条件去掉
                if (!StringUtils.isEmpty(userInfo.getRoleKey())
                        && SysConst.ROLE_KEY_ADMIN.equals(userInfo.getRoleKey())
                        && SysConst.ROLE_KEY_SUPER_ADMIN.equals(userInfo.getRoleKey())) {
                    userInfo.setRoleKey(null);
                }
            } else {
                userInfo = new SysUserInfo();
            }
            // 构建查询条件，只查询学生和老师信息
            ArrayList<String> roleKeyList = new ArrayList<>();
            roleKeyList.add(SysConst.ROLE_KEY_STUDENT);
            roleKeyList.add(SysConst.ROLE_KEY_TEACHER);
            userInfo.setRoleKeyList(roleKeyList);

            //分页查询
            if (param.containsKey(SysConst.PAGA_CURRENT_KEY) && param.containsKey(SysConst.PAGA_SIZE_KEY)) {
                IPage<SysUserInfo> userInfoPage = new Page<>();
                userInfoPage.setCurrent(param.getLong(SysConst.PAGA_CURRENT_KEY)).setSize(param.getLong(SysConst.PAGA_SIZE_KEY));
                IPage<SysUserInfo> list = userInfoService.queryByCondition(userInfoPage, userInfo);
                return ResultMsg.success(list);
            } else {  //普通查询
                List<SysUserInfo> list = userInfoService.queryByCondition(userInfo);
                return ResultMsg.success(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.QUERY_FAILURE, StatusCode.QUERY_FAILURE_MSG);
        }
    }


    /**
     * 获取下拉选择的数据
     *
     * @return
     */
    @RequestMapping("/getSelectData")
    public ResultMsg getSelectData() {
        try {
            Map<String, Object> map = userInfoService.getSelectData(SysConst.ROLE_KEY_ADMIN);
            return ResultMsg.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.QUERY_FAILURE, StatusCode.QUERY_FAILURE_MSG);
        }
    }

    /**
     * 保存用户
     *
     * @param userInfo
     * @return
     */
    @PostMapping("/save")
    @Permission
    public ResultMsg save(@RequestBody SysUserInfo userInfo) {
        try {
            if (userInfo == null) {
                return ResultMsg.create(StatusCode.PARAMETER_ERROR, StatusCode.PARAMETER_ERROR_MSG);
            }
            // 判断若添加修改用户为管理员，要进行拦截
            if (roleService.judgeRole(userInfo.getRoleId(), SysConst.ROLE_KEY_SUPER_ADMIN, SysConst.ROLE_KEY_ADMIN)) {
                return ResultMsg.create(StatusCode.INSUFFICIENT_PRIVILEGE, StatusCode.INSUFFICIENT_PRIVILEGE_MESSAGE);
            }
            // 保存用户
            if (!userInfoService.save(userInfo)) {
                return ResultMsg.create(StatusCode.SAVE_FAILURE, StatusCode.SAVE_FAILURE_MSG);
            }
            return ResultMsg.success();
        } catch (OperatorFailureException ofe) {
            ofe.printStackTrace();
            return ResultMsg.create(ofe.getCode(), ofe.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.SAVE_FAILURE, StatusCode.SAVE_FAILURE_MSG);
        }
    }

    /**
     * 删除用户
     *
     * @param param
     * @return
     */
    @DeleteMapping("/delete")
    @Permission
    public ResultMsg delete(@RequestBody JSONObject param) {
        try {
            if (param == null || !param.containsKey(SysConst.BATCH_ID)
                    || !param.getString(SysConst.BATCH_ID).contains(",")) {
                return ResultMsg.create(StatusCode.PARAMETER_ERROR, StatusCode.PARAMETER_ERROR_MSG);
            }
            String ids = param.getString(SysConst.BATCH_ID);
            userInfoService.remove(ids);
            return ResultMsg.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.DELETE_FAILUER, StatusCode.DELETE_FAILUER_MSG);
        }
    }

    /**
     * 修改密码
     *
     * @param authen 封装新旧密码的实体
     * @return 响应码，响应信息
     */

    @PostMapping("/updatePassword")
    @Permission
    public ResultMsg updatePassword(@RequestBody SysUserLocalAuthen authen) {
        try {
            if (authen == null
                    // todo 涉及到密码认证，需要重新设计
                    || StringUtils.isEmpty(authen.getNewPassword())
                    || StringUtils.isEmpty(authen.getPasswdCheck())) {
                return ResultMsg.create(StatusCode.PARAMETER_ERROR, StatusCode.PARAMETER_ERROR_MSG);
            }
            authen.setPassword(authen.getNewPassword());
            userInfoService.updatePassword(authen);
            return ResultMsg.success();
        } catch (OperatorFailureException e) {
            e.printStackTrace();
            return ResultMsg.create(e.getCode(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.SERVER_INNER_ERROR, StatusCode.SERVER_INNER_ERROR_MSG);
        }
    }
}
